package com.npr.controller;

import com.alibaba.fastjson.JSONObject;
import com.npr.util.CommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(){
        return "Hello SpringBoot";
    }
    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response){
        //获取请求数据
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
        Enumeration<String> enumeration =  request.getHeaderNames();
        while (enumeration.hasMoreElements()){//一种老式迭代器
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name+":"+value);
        }
        System.out.println(request.getParameter("code"));
        //返回相应数据
        response.setContentType("text/html;charset=utf-8");//设置返回数据的类型，和字符集
        try (
                PrintWriter writer = response.getWriter();//写在这就不用手动写close了
                )
        {
            writer.write("<h1>牛客网<h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //get请求
    // 带有两个参数，current和limit，/students?current=1&limit=20
    @RequestMapping(path="/students",method= RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(name="current",required = false,defaultValue = "1") int current, int limit){
        /*定义时形参名字与传入参数名字相同，就可以自动匹配。也可以添加注解@RequestParam,name对应传入的名字，这时形参名可以不同。
        required表示是否不为空，defaultValue 默认值。
         */
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }
    //restful风格，/students/123
    @RequestMapping(path="/student/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id")int id){//需要添加注解
        System.out.println(id);
        return "a student";
    }
    //POST请求
    @RequestMapping(path="/student",method=RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age){
        System.out.println(age);
        System.out.println(name);
        return "success";
    }

    //响应HTML数据
    @RequestMapping(path="/teacher",method = RequestMethod.GET)
    public ModelAndView getTeacher(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("name","张三");
        mav.addObject("age",30);
        mav.setViewName("/demo/view");//地址从templates的下一级开始写
        return mav;
    }
    @RequestMapping(path = "/school",method = RequestMethod.GET)
    public String getSchool(Model model){
        model.addAttribute("name","bupt");
        model.addAttribute("age","72");
        return "/de,p/view";
    }
    //响应json数据(异步请求)
    //java对象->JSON字符串->JS对象
    @RequestMapping(path="/emp",method=RequestMethod.GET)
    @ResponseBody//返回json需要加此注解
    public Map<String,Object> getEmp(){
        Map<String,Object> emp = new HashMap<>();
        emp.put("name","张三");
        emp.put("age","23");
        emp.put("salary","5000");
        return emp;
    }
    //cookie示例
    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        //创建cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        //设置cookie生效的范围
        cookie.setPath("/community/alpha");
        //默认关掉浏览器就消失，可以设置生存时间
        cookie.setMaxAge(60*10);//单位是秒
        response.addCookie(cookie);
        return "set cookie";
    }
    @GetMapping("/cookie/get")
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){
        System.out.println(code);
        return "get cookie";
    }
    //Session示例
    @GetMapping("/session/set")
    @ResponseBody
    public String setSession(HttpSession session){//springmvc会注入session
        session.setAttribute("id",1);
        session.setAttribute("name","Test");
        return "set session";
    }
    @GetMapping("/session/get")
    @ResponseBody
    public String getSession(HttpSession session){
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }
    @PostMapping("/ajax")
    @ResponseBody
    public String testAjax(String name, int age){
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0,"操作成功");
    }

}
